package routerProxy

import (
	"gitee.com/kudingc/role_proxy/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"net/http/httputil"
)

// 公共方法，微服务路由的选择与转发
func forwardMicroservice(c *gin.Context, microCode string) {
	var microService models.SysRegService

	microMap := models.RegisteredMicroservice[microCode]

	if microMap == nil {
		// 未注册服务
		c.JSON(http.StatusOK, models.Res{
			State: models.StateErr,
			Msg:   "当前服务未注册！",
		})
		return
	}

	for {
		if models.RegisteredMicroserviceQueue[microCode].Size() == 0 {
			break
		}
		// 从堆栈中弹出最顶上的一个微服务连接对象，如果其没有问题，则将其压入栈底，以便下次调用，否则舍弃
		microRegisteredService := models.RegisteredMicroserviceQueue[microCode].DeQueue().(models.SysRegService)
		if microMap[microRegisteredService.CopyNum].State == models.Online {
			microService = microMap[microRegisteredService.CopyNum]
			models.RegisteredMicroserviceQueue[microCode].EnQueue(microService)
			break
		}
	}

	if microService.State == models.Online {
		// 转发请求
		host := microService.ServiceAddr
		simpleHostProxy := httputil.ReverseProxy{
			Director: func(req *http.Request) {
				req.URL.Scheme = "http"
				req.URL.Host = host
				req.Host = host
			},
		}
		simpleHostProxy.ServeHTTP(c.Writer, c.Request)
	} else {
		// 未注册服务
		c.JSON(http.StatusOK, models.Res{
			State: models.StateErr,
			Msg:   "当前服务未注册！",
		})
	}
}

func UserProxyHeader(c *gin.Context) {
	// 转发路由，这里的"user"即为微服务注册上来的code
	forwardMicroservice(c, "user")
}
